<?php

/**
 * AJAX CRUD Controller Class
 * The following variables are available in this template:
 * - $this: the CrudCode object
 *
 * @author HaoLV
 */
class ProductController extends ControllerBase {

    public function init() {
        ShortUtil::app()->theme = ADMIN_THEME;
        parent::init();
        $this->registerFancybox();
    }

    public function registerFancybox() {
        // Add jQuery library
        // ShortUtil::clientScript()->registerCoreScript('jquery');
        // Add mousewheel plugin (this is optional)
        ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/jquery.mousewheel-3.0.6.pack.js', CClientScript::POS_HEAD);

        // Add fancyBox main JS and CSS files
        ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/jquery.fancybox.js?v=2.0.6');
        ShortUtil::registerCssFile(ShortUtil::themePath() . '/js/fancybox/jquery.fancybox.css?v=2.0.6', 'screen');

        // Add Button helper (this is optional)
        // ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/helpers/jquery.fancybox-buttons.css?v=1.0.2');
        // ShortUtil::registerCssFile(ShortUtil::themePath().'/js/fancybox/helpers/jquery.fancybox-buttons.js?v=1.0.2','screen');
        // Add Thumbnail helper (this is optional)
        // ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/helpers/jquery.fancybox-thumbs.css?v=1.0.2');
        // ShortUtil::registerCssFile(ShortUtil::themePath().'/js/fancybox/helpers/jquery.fancybox-thumbs.js?v=1.0.2','screen');
        // Add Media helper (this is optional)
        // ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/helpers/jquery.fancybox-media.js?v=1.0.0');

        if (isset($_GET['ajax']))
            $this->layout = '//layouts/none';
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array('model' => $this->loadModel($id)));
    }

    /**
     * Creates a new model.
     */
    public function actionCreate() {
        $model 	= new Product;
        $time 	= date('YmdHis', time());
        $imgNm 	= null;
        $imgExt = array("box" => "", "pro" => "", "thumb" => "");

        if (isset($_POST['Product'])) {
            //upload thumb and images

            if (isset($_FILES['Product'])) {
                //Image Name                              || Image Extension                    Datetime
                $imgNm 				= Util::getImageName($_POST['Product']['prod_name']) . IMG_DILIMITER . $time;

                //*****************upload box image
                $imgExt['box']		= self::upload($model, 'box_img', $imgNm);

                //*****************upload prudct image
                $imgExt['pro'] 		= self::upload($model, 'prod_img', $imgNm);

                //*****************upload product thumb
                $imgExt['thumb'] 	= self::upload($model, 'thumb', $imgNm);
            }

            $model->attributes 		= $_POST['Product'];
            $model->img_name 		= $imgNm;
            $model->img_extension 	= json_encode($imgExt);

            if ($model->save()) {
                $this->setFlash('Product has been created.');
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model 	= $this->loadModel($id);
        $imgNm 	= $model->img_name;
        $imgExt = json_decode($model->img_extension, true);
        $imgExt = (!is_array($imgExt)) ? array() : $imgExt;
        $imgExt = array_merge(array("box" => "", "pro" => "", "thumb" => ""), $imgExt);

        if (isset($_POST['Product'])) {
	        if (isset($_FILES['Product'])) {
	            //*****************upload box image
	            $imgExt['box'] 		= self::upload($model, 'box_img', $imgNm, $imgExt['box']);

	            //*****************upload prudct image
	            $imgExt['pro'] 		= self::upload($model, 'prod_img', $imgNm, $imgExt['pro']);

	            //*****************upload product thumb
	            $imgExt['thumb']	= self::upload($model, 'thumb', $imgNm, $imgExt['thumb']);
	        }

            $model->attributes 		= $_POST['Product'];
            $model->img_name 		= $imgNm;
            $model->img_extension 	= json_encode($imgExt);

            if ($model->save()) {
                $this->setFlash('Product has been updated.');
            }
        }

        $this->render('update', array(
            'model' => $model
        ));
    }

    /**
     * upload
     */
    private function upload($model, $type, $imgNm = '', $ext = '') {
        Yii::import('application.extensions.image.Image');

        $typeDefine = array(
            'box_img' 	=> array(
                'prefix' 	=> REFIX_BOX,
                'height' 	=> null,
                'width' 	=> null,
            ),
            'prod_img' 	=> array(
                'prefix' 	=> REFIX_PROD,
                'height' 	=> null,
                'width' 	=> null,
            ),
            'thumb' 	=> array(
                'prefix' 	=> 'temp',
                'height'	=> null,
                'width'		=> null,
            )
        );
        $isInsert 		= ($ext == '') ? true : false;
		$pathUpload 	= ShortUtil::pathUpload('images');
        $image 			= CUploadedFile::getInstance($model, $type);

        if ($image !== null) {
            $prefix = $typeDefine[$type]['prefix'];
            //remove previous image
            if (!$isInsert) {
                $oldImg = $pathUpload . '/' . $imgNm . IMG_DILIMITER . $prefix . "." . $ext;
                if (file_exists($oldImg))
                    unlink($oldImg);
            }

            // upload new image
            $imgUpload 	= $imgNm . IMG_DILIMITER . $prefix . "." . $image->getExtensionName();
            $pathSave 	= $pathUpload . "/" . $imgUpload;
            $imgExt 	= strtolower($image->getExtensionName());
            $image->saveAs($pathSave);

            // Upload slide
            if ($type == 'thumb') {
                list($width, $height, $type, $attr) = getimagesize($pathSave);

                //remove previous image
                if (!$isInsert) {
                    $oldImgSlide = $pathUpload . '/' . $imgNm . IMG_DILIMITER . REFIX_SLIDE . "." . $ext;
                    if (file_exists($oldImgSlide))
                        unlink($oldImgSlide);

                    $oldImgbThum = $pathUpload . '/' . $imgNm . IMG_DILIMITER . REFIX_THUMB . "." . $ext;
	                if (file_exists($oldImgbThum))
	                    unlink($oldImgbThum);
                }


                // upload new image
                $pathSaveSlide 	= $pathUpload . "/" . $imgNm . IMG_DILIMITER . REFIX_SLIDE . "." . $image->getExtensionName();
                // Resize slide
                $imageSlide = new Image($pathSave);
                if ($height > SLIDE_HEIGHT) {
                	$imageSlide->resize(NULL, SLIDE_HEIGHT);
                }
                else if ($width > SLIDE_WIDTH) {
					$imageSlide->resize(SLIDE_WIDTH, NULL);
                }
                $imageSlide->save($pathSaveSlide);


	            // upload new image
                $pathSaveThumb 	= $pathUpload . "/" . $imgNm . IMG_DILIMITER . REFIX_THUMB . "." . $image->getExtensionName();
                // resize thumb
                $imageThumb = new Image($pathSave);
            	if ($height > THUMB_HEIGHT) {
                	$imageThumb->resize(NULL, THUMB_HEIGHT);
                }
                else if ($width > THUMB_WIDTH) {
					$imageThumb->resize(THUMB_WIDTH, NULL);
                }
                $imageThumb->save($pathSaveThumb);

            	//remove temp image
                if (file_exists($pathSave))
               		unlink($pathSave);

            }
        }
        return (isset($imgExt) && trim($imgExt) != "") ? $imgExt : $ext;
    }

    /**
     * Deletes a particular model.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete() {
        if (Yii::app()->request->isPostRequest) {
            $ids = $_POST['chk'];
            if (is_array($ids))
                foreach ($ids as $key) {
                    //get product model
                    $prodModel = Product::model()->findByPk($key);

                    //remove image of product
                    $pathImage 	= ShortUtil::pathUpload('images');
                    //get image extension
                    $imgExt 	= $this->getImageExtensionFromDB($prodModel->img_extension);
                    //get image name
                    $imgNm 		= $prodModel->img_name;

                    if (file_exists($pathImage . "/" . $imgNm . IMG_DILIMITER . REFIX_BOX . "." . $imgExt)) {
                        unlink($pathImage . "/" . $imgNm . IMG_DILIMITER . REFIX_BOX . "." . $imgExt);
                    }
                    //remove slider
                    if (file_exists($pathImage . "/" . $imgNm . IMG_DILIMITER . REFIX_BOX . "." . $imgExt)) {
                        unlink($pathImage . "/" . $imgNm . IMG_DILIMITER . REFIX_BOX . "." . $imgExt);
                    }
                    //remove thumb
                    if (file_exists($pathImage . "/" . $imgNm . IMG_DILIMITER . REFIX_BOX . "." . $imgExt)) {
                        unlink($pathImage . "/" . $imgNm . IMG_DILIMITER . REFIX_BOX . "." . $imgExt);
                    }

                    //delete product
                    $rs = Product::model()->deleteByPk($key);
                }
            if (isset($_GET['ajax'])) {
                echo CHtml::tag('div', array('class' => 'flash-success'), "Term ID #{$key} has been deleted.");
            } else {
                $this->setFlash("Product ID #{$key} has been deleted.");
                $this->redirect(array('index'));
            }
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Manages all models.
     */
    public function actionIndex() {
        $model = new Product('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Product']))
            $model->attributes = $_GET['Product'];

        $this->render('index', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Product::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'product-form') {
            echo CActiveForm::validate($model);
            ShortUtil::app()->end();
        }
    }

    /**
     * Get Image extenion form DB
     */
    private function getImageExtensionFromDB($jsonImgExt, $identifyValue = 'box') {
        $ext = CJSON::decode($jsonImgExt);
        return $ext['box'];
    }
}